//
//  GeoFencing.m
//  gdemm
//
//  Created by 乔明超 on 16/4/11.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "GeoFencing.h"
#import "InboxManager.h"
#import "MessageManager.h"
#import <CoreLocation/CoreLocation.h>
#import "Location.h"
@interface GeoFencing()<CLLocationManagerDelegate>
{
    BOOL    mEnabled;
    BOOL    mLockScreen;
    BOOL    mClearInbox;
    BOOL    mClearMessages;
    BOOL    mWipeData;
    BOOL    isSafe;
    int     mLimitDistance;
    double  mLongitude;
    double  mLatitude;
}
@property (strong,nonatomic) CLLocationManager *locationMgr;
@property (strong,nonatomic) CLLocation *mLocation;
@property (strong,nonatomic) NSMutableArray<Location *> *mLocations;
@end
@implementation GeoFencing
static GeoFencing *_mInstance;

- (CLLocationManager *)locationMgr{
    if (_locationMgr == nil) {
        _locationMgr = [[CLLocationManager alloc]init];
        _locationMgr.delegate = self;
        _locationMgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    }
    return _locationMgr;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        mEnabled = NO;
        mLockScreen = NO;
        mClearInbox = NO;
        mWipeData = NO;
        isSafe = NO;
        mLimitDistance = 0;
        mLongitude = 0.0;
        mLatitude = 0.0;
    }
    return self;
}
+(instancetype)getInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mInstance = [[self alloc]init];
    });
    return _mInstance;
}

- (void)resetMembers{
    mLockScreen = NO;
    mClearInbox = NO;
    mWipeData = NO;
    mClearMessages = NO;
    mLimitDistance = 0;
    mLongitude = 0.0;
    mLatitude = 0.0;
}

/*获取连个经纬度之间的距离*/
- (int)getDistanceBy:(double)lon1 :(double)lat1 :(double)lon2 :(double)lat2{
    CLLocation *orinLocation = [[CLLocation alloc]initWithLatitude:lat1 longitude:lon1];
    CLLocation *curLocation = [[CLLocation alloc]initWithLatitude:lat2 longitude:lon2];
    double distace = [curLocation distanceFromLocation:orinLocation];
    return (int)distace;
}

/*超出地理位置执行操作*/
- (void)doAction{
    //锁屏
    if (mLockScreen) {
        HRLog(@"锁定屏幕");
        
    }
    
    //清除收件箱文件
    if (mClearInbox) {
        [[InboxManager getInstance]deleteLocalFiles];
        HRLog(@"清除收件箱文件");
    }
    
    //清除消息
    if (mClearMessages) {
        [[MessageManager getInstance]clearMessage];
        HRLog(@"清除消息");
    }
    
    //抹除设备上的数据
    if (mWipeData) {
        HRLog(@"抹除设备上的数据");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Reset"]];
        
    }
}


#pragma mark PolicyHandler代理协议的实现

- (NSString *)supportPolicy{
    return GEO_FENCING;
}

- (BOOL)startPolicyWithPolicyType:(NSString *)policyType policyContent:(NSDictionary*)policyContent{
    //HRLog(@"GeoFencingContent = %@",policyContent);
    [self resetMembers];
    BOOL validPolicy = YES;
    if (self.mLocations == nil) {
        self.mLocations = [NSMutableArray array];
        
    }else{
        [self.mLocations removeAllObjects];
    }

    NSArray *locationArr = [policyContent objectForKey:@"location"];
    for (int i = 0; i < locationArr.count; i++) {
        NSString *longitude = [locationArr[i] objectForKey:@"longitude"];
        NSString *latitude = [locationArr[i] objectForKey:@"latitude"];
        mLimitDistance = [[locationArr[i] objectForKey:@"limitDistance"] intValue];
        //HRLog(@"------%@--%@---%d",longitude,latitude,mLimitDistance);
        /*默认是东经北纬*/
        BOOL east = YES;
        BOOL north = YES;
        
        /*获取位置的东经北纬*/
        unichar we = [longitude characterAtIndex:0];
        unichar ns = [latitude characterAtIndex:0];
        if (we == 'W' || we == 'w') {
            east = NO;
        }
        
        if (ns == 'S' || ns == 's') {
            north = NO;
        }
        
        /*截取位置的经度和纬度,如经度和纬度没有标明,则不需要截取,默认为东经北纬*/
        if (we > '9' || we < '0') {
            mLongitude = [[longitude substringFromIndex:1] doubleValue];
        }else{
            mLongitude = [longitude doubleValue];
        }
        
        if (ns > '9' || ns < '0') {
            mLatitude = [[latitude substringFromIndex:1]doubleValue];
        }else{
            mLatitude = [latitude doubleValue];
        }
        
        
        /*西经为负,南纬为负*/
        if (!east) {
            mLongitude  = 0.0 - mLongitude;
        }
        
        if (!north) {
            mLatitude   = 0.0 - mLatitude;
        }
        Location *loc = [[Location alloc]init];
        loc.mLatitude = mLatitude;
        loc.mLongitude = mLongitude;
        loc.mLimitDistance = mLimitDistance;
        [self addLocation:loc];
        
    }

    
    NSArray *actionsArr = [policyContent objectForKey:@"actions"];
    for (int i = 0; i < actionsArr.count; i++) {
        NSString *action = actionsArr[i];
        if ([action isEqualToString:@"lockScreen"]) {
            mLockScreen = YES;
        }else if ([action isEqualToString:@"clearInbox"]){
            mClearInbox = YES;
        }else if ([action isEqualToString:@"clearMessages"]){
            mClearMessages = YES;
        }else if ([action isEqualToString:@"wipeData"]){
            mWipeData = YES;
        }else{
            validPolicy = NO;
        }

        
    }

    
    /*策略合法且有至少任意一种处理动作则认应该执行*/
    mEnabled = validPolicy && (mLockScreen || mClearInbox || mClearMessages || mWipeData);
    if (mEnabled) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
                [self.locationMgr requestAlwaysAuthorization];
            }else{
                [self.locationMgr startUpdatingLocation];
            }
        });
        
        
    }
    return NO;
    
}

/*停止地理围栏策略的代理的实现*/
- (BOOL)stopPolicyWithPolicyType:(NSString *)policyType{
    mEnabled = NO;
    [self.locationMgr stopUpdatingLocation];
    return NO;
}


/*添加location*/
- (void)addLocation:(Location *)loc{
    if (self.mLocations != nil) {
        if (self.mLocations.count == 0) {
            [self.mLocations addObject:loc];
        }else{
            [self.mLocations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![obj isEqual:loc]) {
                    [self.mLocations addObject:loc];
                }
                
            }];
        }
        
    }
}

#pragma mark FastTask代理的实现
- (BOOL)valid{
    return mEnabled;
}

- (void)run{
    if (self.mLocation != nil) {
        isSafe = NO;
        for (int i = 0; i < self.mLocations.count; i++) {
            int distance = [self getDistanceBy:self.mLocations[i].mLongitude :self.mLocations[i].mLatitude :self.mLocation.coordinate.longitude :self.mLocation.coordinate.latitude];
            if (distance <= self.mLocations[i].mLimitDistance) {
                isSafe = YES;
                break;
            }
            
        }
        if (!isSafe) {
            [self doAction];
        }
    }
    
}


#pragma mark CLLocationManager代理的实现

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    
    if (status == kCLAuthorizationStatusNotDetermined) {
        HRLog(@"定位开始授权");
    
    }else if (status == kCLAuthorizationStatusAuthorizedAlways ||
              status == kCLAuthorizationStatusAuthorizedWhenInUse)
        
    {
        HRLog(@"定位授权成功");
        // 开始定位
        [self.locationMgr startUpdatingLocation];
        
    }else
    {
        HRLog(@"定位授权失败");
    }
    
}
/*定位位置信息的获取*/
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    HRLog(@"经度= %f,纬度 = %f",[locations lastObject].coordinate.longitude,[locations lastObject].coordinate.latitude);
    
    self.mLocation  = [locations lastObject];


}
@end
